package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.blue.ui.DynamicWaveFormView;
import androidx.appcompat.app.AlertDialog;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;


public class MagCorActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "MagCorActivity";
    private Button startButton;
    private String deviceId;
    private  BluetoothService bluetoothService;
    private boolean isBound = false;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private Thread workerThreadx;
    private Thread workerThready;
    private Thread workerThreadz;
    private Boolean runningx=false;
    private Boolean runningy=false;
    private Boolean runningz=false;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private DataProcessorManager processorManager;
    private final ConcurrentLinkedQueue<Float> magxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magzDataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();
//    private ConcurrentLinkedQueue<byte[]> dataQueue2 = new ConcurrentLinkedQueue<>();
private LinkedBlockingDeque<byte[]> dataQueue = new LinkedBlockingDeque<>();
    private LinkedBlockingDeque<byte[]> dataQueue2 = new LinkedBlockingDeque<>();
    private Integer conDeviceNum=1;
    private String deviceMacLeft;
    private String deviceMacRight;
    private Integer handDir=0;
    private AlertDialog myDialog;
    private Button leftButton;
    private Button rightButton;
    private Boolean isLeftDeviceReceived=false;
    private Boolean isRightDeviceReceived=false;

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            if(conDeviceNum==1){
                if(handDir==1) {
                    dataQueue  = bluetoothService.getDataQueueLeft();
                    processorManager = DataProcessorManager.getInstance(dataQueue);
                }else{
                    dataQueue2  = bluetoothService.getDataQueueRight();
                    processorManager = DataProcessorManager.getInstance(dataQueue2);
                }
            }
            else{
                dataQueue  = bluetoothService.getDataQueueLeft();
                dataQueue2  = bluetoothService.getDataQueueRight();
            }
           // dataQueue  = bluetoothService.getDataQueue();
//            bluetoothService.setOnDataReceiveListener((data, deviceIndex) -> {
//                System.out.println("MagCorActivity----:"+deviceIndex);
//                 String hex = utils.bytesToHex(data);
//                 System.out.println("MagCorActivity----:"+hex);
//                runOnUiThread(() -> {
//                    if(deviceIndex==1) {
//                        dataQueue.add(data);
//                    }
//                    if(deviceIndex==2) {
//                        dataQueue2.add(data);
//                    }
//                });
//            });
//                processorManager = DataProcessorManager.getInstance(dataQueue);
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
            Log.d("ServiceTest", "Service disconnected");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CrashHandler.getInstance().init(this);
        setContentView(R.layout.activity_mag_cor);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("磁力计校准");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        conDeviceNum = sp.getInt("conDeviceNum", 1);
        isLeftDeviceReceived=sp.getBoolean("isLeftDeviceReceived",false);
        isRightDeviceReceived=sp.getBoolean("isRightDeviceReceived",false);
        if(conDeviceNum==1) {

            handDir = sp.getInt("handDirection",0);
            if(handDir==1){
                if(isLeftDeviceReceived==false){
                    Toast.makeText(MagCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_LEFT", "");
            }else{
                if(isRightDeviceReceived==false){
                    Toast.makeText(MagCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                }
                deviceId = sp.getString("DEVICE_ADDRESS_RIGHT", "");
            }

        }
        if(conDeviceNum==2){
            if(isLeftDeviceReceived==false){
                Toast.makeText(MagCorActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }else if(isRightDeviceReceived==false){
                Toast.makeText(MagCorActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
            }
            deviceMacLeft = sp.getString("DEVICE_ADDRESS_LEFT","");
            deviceMacRight=sp.getString("DEVICE_ADDRESS_RIGHT","");
            System.out.println("magcor----deviceMacLeft:"+deviceMacLeft);
            System.out.println("magcor----deviceMacRight:"+deviceMacRight);
//            if (deviceMacLeft == null || deviceMacLeft.isEmpty() || deviceMacRight == null || deviceMacRight.isEmpty()) {
//                Toast.makeText(MagCorActivity.this, "未获取到蓝牙MAC地址，请重新连接", Toast.LENGTH_SHORT).show();
//            }

        }

        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("X轴磁力计(高斯)");
        waveformViewX.setYRange(-2,2);
        waveformViewY.setYtitle("Y轴磁力计(高斯)");
        waveformViewY.setYRange(-2,2);
        waveformViewZ.setYtitle("Z轴磁力计(高斯)");
        waveformViewZ.setYRange(-2,2);

        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX.clearDataPoints();
                    waveformViewY.clearDataPoints();
                    waveformViewZ.clearDataPoints();
                }
                selectedSensorNum=position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        View customView = LayoutInflater.from(this).inflate(R.layout.dialog_custom, null);
        myDialog = new AlertDialog.Builder(MagCorActivity.this)
                .setView(customView)
                .create();
        leftButton=customView.findViewById(R.id.leftBtn);
        rightButton=customView.findViewById(R.id.rightBtn);
        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                processorManager = DataProcessorManager.getInstance(dataQueue);
                String mac = deviceMacLeft.replace(":", "");
                processorManager.setDeviceMac(mac);
                processorManager.temp=handDir;
                processorManager.setDataUpdateListener(MagCorActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.MagBias);
                myDialog.dismiss();
            }
        });
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                processorManager = DataProcessorManager.getInstance(dataQueue2);
                String mac = deviceMacRight.replace(":", "");
                processorManager.setDeviceMac(mac);
                processorManager.temp=handDir;
                processorManager.setDataUpdateListener(MagCorActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.MagBias);
                myDialog.dismiss();
            }
        });

        startButton = findViewById(R.id.magCorrectBtn);
        startButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    if (conDeviceNum == 2) {
                        if(isLeftDeviceReceived==false){
                            Toast.makeText(MagCorActivity.this, "左手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                        }else if(isRightDeviceReceived==false){
                            Toast.makeText(MagCorActivity.this, "右手设备未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                        }else {
                            myDialog.show();
                        }
//                    AlertDialog.Builder builder = new AlertDialog.Builder(MagCorActivity.this);
//                    builder.setTitle("请选择")
//                            .setItems(new String[]{"左手", "右手"}, (dialog, which) -> {
//                                if (which == 0) {
//                                    Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
//                                    processorManager = DataProcessorManager.getInstance(dataQueue);
//                                    String mac = deviceMacLeft.replace(":", "");
//                                    processorManager.setDeviceMac(mac);
//                                    processorManager.temp=handDir;
//                                    processorManager.setDataUpdateListener(MagCorActivity.this);
//                                    processorManager.startProcessing();
//                                    processorManager.setProcessingFunction(ProcessingFunction.MagBias);
//                                } else {
//                                    Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
//                                    processorManager = DataProcessorManager.getInstance(dataQueue2);
//                                    String mac = deviceMacRight.replace(":", "");
//                                    processorManager.setDeviceMac(mac);
//                                    processorManager.temp=handDir;
//                                    processorManager.setDataUpdateListener(MagCorActivity.this);
//                                    processorManager.startProcessing();
//                                    processorManager.setProcessingFunction(ProcessingFunction.MagBias);
//                                }
//                            })
//                            .setNegativeButton("取消", null)
//                            .show();
                    } else {

                        if(handDir==1){
                            if(isLeftDeviceReceived==false){
                                Toast.makeText(MagCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        if(handDir==2){
                            if (isRightDeviceReceived == false) {
                                Toast.makeText(MagCorActivity.this, "未收到蓝牙数据，请重启设备重新连接", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                            Toast.makeText(MagCorActivity.this, "开始校准", Toast.LENGTH_SHORT).show();
                            //processorManager = DataProcessorManager.getInstance(dataQueue);
                            String mac = deviceId.replace(":", "");
                            System.out.println("magcor----mac:" + mac);
                            processorManager.setDeviceMac(mac);
                            processorManager.setDataUpdateListener(MagCorActivity.this);
                            processorManager.startProcessing();
                            processorManager.setProcessingFunction(ProcessingFunction.MagBias);

                    }

            }
        });

    }
    @Override
    protected void onStart() {
        super.onStart();
        if(conDeviceNum==1) {
            if(handDir==1) {
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_LEFT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }else{
                Intent intent = new Intent(this, BluetoothService.class);
                intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceId);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        }
        if(conDeviceNum==2) {
            Intent intent = new Intent(this, BluetoothService.class);
            intent.putExtra("DEVICE_ADDRESS_LEFT", deviceMacLeft);
            intent.putExtra("DEVICE_ADDRESS_RIGHT", deviceMacRight); // 如果需要
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
        }
    }
    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getValue();
        System.out.println("processedValue:"+processedValue);
        String flag = data.getFlag();
        System.out.println("magcor-Flag:"+flag);
        if(flag.equals("rawout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
          //  System.out.println("dataArr: " + dataArr);
            switch(selectedSensorNum){
                case 0:
                    String da1 = dataArr[6].length()>10?dataArr[6].substring(0,8):dataArr[6];
                    String da2 = dataArr[7].length()>10?dataArr[7].substring(0,8):dataArr[7];
                    String da3 = dataArr[8].length()>10?dataArr[8].substring(0,8):dataArr[8];
                    if(!da1.equals("0")) {
                        System.out.println("magcor-Hex: " + processedValue);
                       // magxDataQueue.add(Float.parseFloat(da1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(da1) * 10000);
                    }
                    if(!da2.equals("0")) {
                       // magyDataQueue.add(Float.parseFloat(da2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(da2) * 10000);
                    }
                    if(!da3.equals("0")) {
                       // magzDataQueue.add(Float.parseFloat(da3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(da3) * 10000);
                    }
                    break;
                case 1:
                    String dd1 = dataArr[15].length()>10?dataArr[15].substring(0,8):dataArr[15];
                    String dd2 = dataArr[16].length()>10?dataArr[16].substring(0,8):dataArr[16];
                    String dd3 = dataArr[17].length()>10?dataArr[17].substring(0,8):dataArr[17];

                    if(!dd1.equals("0")) {
                       // magxDataQueue.add(Float.parseFloat(dd1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(dd1) * 10000);

                    }
                    if(!dd2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(dd2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(dd2) * 10000);

                    }
                    if(!dd3.equals("0")) {
//                        magzDataQueue.add(Float.parseFloat(dd3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(dd3) * 10000);

                    }
                    break;
                case 2:
                    String de1 = dataArr[24].length()>10?dataArr[24].substring(0,8):dataArr[24];
                    String de2 = dataArr[25].length()>10?dataArr[25].substring(0,8):dataArr[25];
                    String de3 = dataArr[26].length()>10?dataArr[26].substring(0,8):dataArr[26];
                    if(!de1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(de1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(de1) * 10000);

                    }
                    if(!de2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(de2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(de2) * 10000);

                    }

                    if(!de3.equals("0")) {
//                        magzDataQueue.add(Float.parseFloat(de3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(de3) * 10000);

                    }
                    break;
                case 3:
                    String df1 = dataArr[33].length()>10?dataArr[33].substring(0,8):dataArr[33];
                    String df2 = dataArr[34].length()>10?dataArr[34].substring(0,8):dataArr[34];
                    String df3 = dataArr[35].length()>10?dataArr[35].substring(0,8):dataArr[35];
                    if(!df1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(df1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(df1) * 10000);

                    }
                    if(!df2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(df2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(df2) * 10000);

                    }
                    if(!df3.equals("0")) {
//                        magzDataQueue.add(Float.parseFloat(df3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(df3) * 10000);

                    }
                    break;
                case 4:
                    String dc1 = dataArr[42].length()>10?dataArr[42].substring(0,8):dataArr[42];
                    String dc2 = dataArr[43].length()>10?dataArr[43].substring(0,8):dataArr[43];
                    String dc3 = dataArr[44].length()>10?dataArr[44].substring(0,8):dataArr[44];
                    if(!dc1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(dc1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(dc1) * 10000);

                    }
                    if(!dc2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(dc2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(dc2) * 10000);

                    }
                    if(!dc3.equals("0")) {
//                        magzDataQueue.add(Float.parseFloat(dc3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(dc3) * 10000);

                    }
                    break;
                case 5:
                    String db1 = dataArr[51].length()>10?dataArr[51].substring(0,8):dataArr[51];
                    String db2 = dataArr[52].length()>10?dataArr[52].substring(0,8):dataArr[52];
                    String db3 = dataArr[53].length()>10?dataArr[53].substring(0,8):dataArr[53];
                    if(!db1.equals("0")) {
//                        magxDataQueue.add(Float.parseFloat(db1) * 10000);
                        waveformViewX.addDataPoint(Float.parseFloat(db1) * 10000);

                    }
                    if(!db2.equals("0")) {
//                        magyDataQueue.add(Float.parseFloat(db2) * 10000);
                        waveformViewY.addDataPoint(Float.parseFloat(db2) * 10000);

                    }
                    if(!db3.equals("0")) {
//                        magzDataQueue.add(Float.parseFloat(db3) * 10000);
                        waveformViewZ.addDataPoint(Float.parseFloat(db3) * 10000);
                    }
                    break;
            }

        }
        if(flag.equals("NaN")){
            Toast.makeText(MagCorActivity.this,"校准不充分，请重新校准",Toast.LENGTH_SHORT).show();
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
        }
        if(flag.equals("magbias")){
//            String[] magres = processedValue.split("\n");
//            System.out.println("magcor"+magres[0]+" "+magres[1]+" "+magres[2]);
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
            //跳转到结果页面
            Intent intent = new Intent(MagCorActivity.this, MagResActivity.class);
            intent.putExtra("magResult",processedValue);
            startActivity(intent);

        }
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onStop() {
        super.onStop();
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
            processorManager.setProcessingFunction(ProcessingFunction.Blank);
            processorManager.setzero();
            processorManager.stopProcessing();

    }
}